package updown.handler.auth;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import updown.domain.Account;
import updown.service.task.LoginService;
import updown.util.JwtokenUtil;
import updown.util.ServerContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: ww.kaixin.downupservice.handler </p>
 * <p>Description:updown: - 登录拦截器 </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/5
 * @Version: 1.0
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginService loginService;

    private final Cache<String, Account> userCache = CacheBuilder
            .newBuilder()
            .maximumSize(10)
            .expireAfterAccess(60, TimeUnit.MINUTES)
            .build();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0){
            response.getWriter().print("用户未登录，请登录后操作！");
            return false;
        }
        String token = null;
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("token")){
                token = cookies[i].getValue();
            }
        }
        if (StringUtils.isEmpty(token)) {
            response.getWriter().print("用户未登录，请登录后操作！");
            return false;
        }

        String userName = JwtokenUtil.getUserName(token);
        Account account = userCache.getIfPresent(userName);
        if (account == null){
            Account accountInData = loginService.getAccountByToken(token);
            if(accountInData == null){
                response.getWriter().print("token错误，请查重新登录");
                return false;
            }else {
                userCache.put(accountInData.getUsername(),accountInData);
            }
        }
        ServerContextHolder.getContext().setUserName(userName);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
